<template>
  <div class="about">
    <h1>{{id ? '编辑' : '新建'}}攻略</h1>
    <el-form label-width="120px" @submit.native.prevent="save">
      <el-form-item label="分类">
        <el-input v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item label="攻略列表">
        <el-button @click="model.itemsArr.push({})"><i class="el-icon-plus"></i> 添加攻略</el-button>
          <el-row type="flex" style="flex-wrap:wrap">
            <el-col :md="24" v-for="(item, i) in model.itemsArr" :key="i">
              <el-form-item label="标题">
                <el-input v-model="item.title"></el-input>
              </el-form-item>
              <el-form-item label="图片地址">
                <el-input v-model="item.img"></el-input>
              </el-form-item>
              <el-form-item label="详情">
                <vue-editor v-model="item.body" />
              </el-form-item>
              <el-form-item>
                <el-button size="small" type="danger" @click="model.itemsArr.splice(i,1)">删除</el-button>
              </el-form-item>
            </el-col>
          </el-row>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
//引入富文本编辑器，并要在下边注册一下子组件
import { VueEditor } from "vue2-editor"
export default {
  components: { 
    VueEditor
  },
  props:{
    id:{}
  },
  data() {
    return {
      model: {
        itemsArr: []
      },
    }
  },
  methods: {
    //async，await将异步方法改为类同步方法，内部也会返回promise  
    //保存添加列表,编辑完保存列表（两种处理在一个方法中完成）
    async save() {
      let res
      if(this.id) {
        res = await this.$http.put(`rest/strategy/${this.id}`, this.model)
      } else {
        res = await this.$http.post("rest/strategy", this.model)
      }
      if (res.status === 200) {
        //编程式导航，请求成功后跳转到list页面
        this.$router.push("/strategy/list")
        //element封装的方法,提示用户保存成功
        this.$message({
          type: "success",
          message: "保存成功"
        })
      }
    },
    //编辑列表时获取原本的数据
    async fetch() {
      const res = await this.$http.get(`rest/strategy/${this.id}`)
      this.model = Object.assign({}, this.model, res.data)  
    }
  },
  created() {
    //为编辑分类时获取数据,&&表示满足前面的条件之后
    this.id && this.fetch()
  },
}
</script>
